package com.kld.shop.controller.admin;

import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.util.DateUtil;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ISysDictService;
import com.kld.sys.po.SysDict;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Dan on 2015/8/3.
 */
@Controller
@RequestMapping("/admin/sysDict")
public class SysDictController extends BaseController {

    @Resource
    private ISysDictService sysDictService;


    @RequestMapping("dictList")
    public String dictList() {
        return "admin/dict/dictsList";
    }

    /**
     * 创建字典项
     *
     * @param dict
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "createDict", method = RequestMethod.POST)
    public ResultMsg createDict(SysDict dict) {
        ResultMsg rmsg = new ResultMsg();
        dict.setCreatetime(DateUtil.getDate());
//        dict.setCreator(getUserDetails().getUsername());
        dict.setIsvalid(1);
        dict.setIssystem(0);
        int r = sysDictService.insert(dict);

        if (r > 0) {
            rmsg.setResult(true);
            rmsg.setMsg("新建成功");
        } else {
            rmsg.setResult(false);
            rmsg.setMsg("新建失败");
        }

        return rmsg;
    }

    /**
     * 更新字典项
     *
     * @param newdict
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "updateDict", method = RequestMethod.POST)
    public ResultMsg updateDict(SysDict newdict) {
        ResultMsg rmsg = new ResultMsg();
        SysDict dict = sysDictService.getSysDict(newdict.getDictcode());
        if (dict == null) {
            rmsg.setResult(false);
            rmsg.setMsg("字典不存在");
            return rmsg;
        }
        dict.setName(newdict.getName());
        dict.setValue(StringUtils.isNotBlank(newdict.getValue()) ? newdict.getValue() : "");
        dict.setRemark(StringUtils.isNotBlank(newdict.getRemark()) ? newdict.getRemark() : "");
        dict.setAlias(StringUtils.isNotBlank(newdict.getAlias()) ? newdict.getAlias() : "");
        dict.setOrderno(newdict.getOrderno());
        dict.setModifier(getUserName());
        dict.setModitime(DateUtil.getDate());
        try {
            int upd = sysDictService.update(dict);
            if (upd > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("编辑成功");
            } else {
                rmsg.setResult(false);
                rmsg.setMsg("编辑失败");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }
        return rmsg;
    }

    /**
     * 逻辑删除字典
     *
     * @param dictcode
     * @return
     */
    @ResponseBody()
    @RequestMapping("deleteDict")
    public ResultMsg deleteDict(int dictcode) {
        ResultMsg rmsg = new ResultMsg();
        SysDict dict = sysDictService.getSysDict(dictcode);
        if (dict == null) {
            rmsg.setResult(false);
            rmsg.setMsg("字典不存在");
            return rmsg;
        }
        try {
            int upd = sysDictService.updateValidState(dict.getDictcode(), 0);
            if (upd > 0) {
                rmsg.setResult(true);
                rmsg.setMsg("删除成功");
            } else {
                rmsg.setResult(false);
                rmsg.setMsg("删除失败");
            }
        } catch (Exception ex) {
            rmsg.setResult(false);
            rmsg.setMsg(ex.getMessage());
        }

        return rmsg;
    }

    /**
     * 字典树形列表
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("getDictTree")
    public String getDictTree() {
        JSONArray arr = new JSONArray();
        //增加默认
        JSONObject jsod = new JSONObject();
        jsod.put("id", 0);
        jsod.put("text", "字典");
        jsod.put("children", getParentDictArray(0));
        arr.add(jsod);
        String str = String.format("%s", arr);
        return str;
    }

    /**
     * 获取父级
     *
     * @param parentcode
     * @return
     */
    public JSONArray getParentDictArray(Integer parentcode) {
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentcode", parentcode);
        map.put("isvalid", 1);
        List<SysDict> sysDictList = sysDictService.getSysDictList(map);
        for (SysDict dict : sysDictList) {
            JSONObject json = new JSONObject();
            json.put("id", dict.getDictcode());
            json.put("text", dict.getName());

            JSONArray chilerenCategory = getParentDictArray(dict.getDictcode());
            if (chilerenCategory.size() > 0) {
                json.put("children", chilerenCategory);
                json.put("state", "closed");
            }

            jsonArray.add(json);
        }
        return jsonArray;
    }

    @ResponseBody()
    @RequestMapping("getDictTreeList")
    public String getDictTreeList() {
        JSONArray jsonArray = new JSONArray();
        jsonArray = getDictTreeArray(0);
        String res = String.format("%s", jsonArray);
        return res;
    }


    /**
     * 获取全部字典
     *
     * @param parentcode
     * @return
     */
    public JSONArray getDictTreeArray(Integer parentcode) {
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentcode", parentcode);
        map.put("isvalid", 1);
        List<SysDict> dictList = sysDictService.getSysDictList(map);
        if (dictList.size() > 0) {
            for (SysDict dict : dictList) {
                JSONObject json = new JSONObject();
                json.put("dictcode", dict.getDictcode());
                json.put("parentcode", dict.getParentcode());
                json.put("name", dict.getName());
                json.put("value", dict.getValue());
                json.put("alias", dict.getAlias());
                json.put("remark", dict.getRemark());
                json.put("orderno", dict.getOrderno());
                JSONArray childrenDict = getDictTreeArray(dict.getDictcode());
                if (childrenDict.size() > 0) {
                    json.put("children", childrenDict);
                    json.put("state", "closed");
                }
                jsonArray.add(json);
            }
        }
        return jsonArray;
    }

    /**
     * 获取字典选择项
     *
     * @param parentcode
     * @return
     */
    public JSONArray getSelectedDictTreeArray(Integer parentcode) {
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentcode", parentcode);
        List<SysDict> dictList = sysDictService.getSysDictList(map);
        if (dictList.size() > 0) {
            for (SysDict dict : dictList) {
                JSONObject json = new JSONObject();
                json.put("id", dict.getDictcode());
                json.put("text", dict.getName());
                JSONArray childrenDict = getDictTreeArray(dict.getDictcode());
                if (childrenDict.size() > 0) {
                    json.put("children", childrenDict);
                    json.put("state", "closed");
                }
                jsonArray.add(json);
            }
        }
        return jsonArray;
    }

    @ResponseBody()
    @RequestMapping("getSysDictListByPcode")
    public List<SysDict> getSysDictListByPcode() {
        Map<String, Object> map = new HashMap<String, Object>();
        SysDict sys_dict = sysDictService.getSysDictByAlias("dhqt");
        List<SysDict> sys_dictList = new ArrayList<SysDict>();
        if (sys_dict != null) {
            sys_dictList = sysDictService.getSysDictListByPcode(sys_dict.getDictcode());
        }
        return sys_dictList;
    }

    @ResponseBody()
    @RequestMapping("getSysDictListByPAliase")
    public List<SysDict> getSysDictListByPAlias(String alias) {
        Map<String, Object> map = new HashMap<String, Object>();
        SysDict sys_dict = sysDictService.getSysDictByAlias(alias);
        List<SysDict> sys_dictList = new ArrayList<SysDict>();
        if (sys_dict != null) {
            sys_dictList = sysDictService.getSysDictListByPcode(sys_dict.getDictcode());
        }
        return sys_dictList;
    }
}